package com.danco.training.zaneuskaya.controller.book;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;



import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.danco.training.zaneuskaya.api.AudtorService;
import com.danco.training.zaneuskaya.api.BookService;
import com.danco.training.zaneuskaya.controller.GenericController;
import com.danco.training.zaneuskaya.domain.Auditor;
import com.danco.training.zaneuskaya.domain.Book;
import com.danco.training.zaneuskaya.service.impl.AuditorServiceImpl;
import com.danco.training.zaneuskaya.service.impl.BookServiceImpl;

@SuppressWarnings("serial")
public class BookCreateController extends GenericController {

	private static final String BOOK_LIST_URL = "/book/list";
	private static final String ACTION_AUDIT_CREATE_BOOK = "CREATE BOOK";
	private static final String BOOK_QUANTITY = "book_quantity";
	private static final String BOOK_PRICE = "book_price";
	private static final String PUB_DATE = "pub_date";
	private static final String BOOK_AUTHOR = "book_author";
	private static final String BOOK_TITLE = "book_title";
	private static final String BOOK_CREATE_JSP = "/WEB-INF/views/book/create.jsp";
	private static final String DATE_PATTERN = "yyyy-MM-dd";
	private BookService bookService;
	private AudtorService auditorService;
	private SimpleDateFormat formatter = new SimpleDateFormat(DATE_PATTERN);

	public BookCreateController() {
		super();
		bookService = BookServiceImpl.getBookStorageSeviceImplInstance();
		auditorService = new AuditorServiceImpl(); 
	}


	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		getServletContext().getRequestDispatcher(BOOK_CREATE_JSP).forward(
				request, response);

	}
	
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		
		String title = request.getParameter(BOOK_TITLE);
		String author = request.getParameter(BOOK_AUTHOR);
		
		String pubDate = request.getParameter(PUB_DATE);
		Date publicationDate = null;
		try {
			publicationDate = formatter.parse(pubDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		double price = Double.parseDouble(request.getParameter(BOOK_PRICE));
		int quantity = Integer.parseInt(request.getParameter(BOOK_QUANTITY));

		Book book = new Book(title, author, publicationDate, price, true,
				quantity, new Date());
		
		bookService.addEntity(book);
		auditorService.addEntity(new Auditor(new Date(), null, ACTION_AUDIT_CREATE_BOOK));
		response.sendRedirect(BOOK_LIST_URL );
		
	}
	
	
}
